<template>
  <div v-if="visible" class="modal-overlay" @click.self="closeDialog">
    <div class="modal">
      <span class="modal-close-button" @click="closeDialog">X</span>
      <h2>注册</h2>
      <form @submit.prevent="processRegister">
        <!-- 头像上传 -->
        <div class="input-group avatar-upload">
          <el-upload
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :auto-upload="false"
            :on-change="handleAvatarChange"
            accept="image/jpeg,image/png"
          >
            <img v-if="avatarPreview" :src="avatarPreview" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            <div class="upload-hint">点击上传头像</div>
          </el-upload>
          <div class="avatar-tips">支持JPG/PNG格式，大小不超过2MB</div>
        </div>
        <div class="input-group">
          <el-autocomplete
            v-model="schoolInput"
            :fetch-suggestions="fetchSchools"
            clearable
            placeholder="请输入学校"
            @select="handleSchoolSelect"
          />
        </div>
        <div class="input-group">
          <el-input v-model="registerUsername" placeholder="请输入用户名" />
        </div>
        <div class="input-group">
          <el-input v-model="nickname" placeholder="请输入昵称" />
        </div>
        <div class="input-group">
          <el-input v-model="number" placeholder="请输入编号" />
        </div>
        <div class="input-group">
          <el-select v-model="sex" clearable placeholder="请选择性别">
            <el-option 
              v-for="option in sexOptions" 
              :key="option.value" 
              :label="option.label" 
              :value="option.value" 
            />
          </el-select>
        </div>
        <div class="input-group">
          <el-select 
            v-model="grade" 
            clearable 
            placeholder="请选择年级"
            class="full-width-select"
          >
            <el-option
              v-for="option in gradeOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </div>
        <div class="input-group">
          <el-autocomplete
            v-model="majorInput"
            :fetch-suggestions="fetchMajors"
            clearable
            placeholder="请输入专业"
            @select="handleMajorSelect"
          />
        </div>
        <div class="input-group">
          <el-input
            :type="showRegisterPassword ? 'text' : 'password'"
            v-model="registerPassword"
            :class="{ 'input-error': !isPasswordValid }"
            placeholder="请输入密码"
            @input="validatePassword"
          >
            <template #suffix>
              <el-icon class="toggle-password" @click="toggleRegisterPasswordVisibility">
                <View v-if="!showRegisterPassword" />
                <Hide v-else />
              </el-icon>
            </template>
          </el-input>
          <span v-if="!isPasswordValid" class="error-message">密码必须包含至少8个字符,包括字母和数字</span>
        </div>
        <div class="input-group">
          <el-input
            :type="showConfirmPassword ? 'text' : 'password'"
            v-model="confirmPassword"
            placeholder="确认密码"
          >
            <template #suffix>
              <el-icon class="toggle-password" @click="toggleConfirmPasswordVisibility">
                <View v-if="!showConfirmPassword" />
                <Hide v-else />
              </el-icon>
            </template>
          </el-input>
        </div>
        <el-button type="primary" @click="processRegister">注册</el-button>
      </form>
    </div>
  </div>
</template>

<script>
import { defineComponent, ref } from 'vue';
import axios from 'axios';
import { 
  ElIcon, 
  ElMessage, 
  ElButton, 
  ElInput, 
  ElAutocomplete, 
  ElSelect, 
  ElOption,
  ElUpload 
} from 'element-plus';
import { Hide, View, Plus } from '@element-plus/icons-vue';

export default defineComponent({
  name: 'RegisterForm',
  components: {
    ElIcon,
    ElInput,
    ElButton,
    ElAutocomplete,
    ElSelect,
    ElOption,
    ElUpload,
    View,
    Hide,
    Plus
  },
  props: {
    visible: Boolean,
  },
  emits: ['close'],
  setup(props, { emit }) {
    // 表单数据
    const registerUsername = ref('');
    const nickname = ref('');
    const number = ref('');
    const sex = ref('');
    const majorInput = ref('');
    const registerPassword = ref('');
    const confirmPassword = ref('');
    const avatarFile = ref(null);
    const avatarPreview = ref('');
    const grade = ref('');
     const schoolInput = ref('');
    // 状态管理
    const showRegisterPassword = ref(false);
    const showConfirmPassword = ref(false);
    const isPasswordValid = ref(true);
    
    // 选项数据
    const sexOptions = [
      { value: '01', label: '男' },
      { value: '02', label: '女' },
    ];

    // 密码验证正则
    const passwordRegex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/;

    const gradeOptions = [
  { value: '大一', label: '大一' },
  { value: '大二', label: '大二' },
  { value: '大三', label: '大三' },
  { value: '大四', label: '大四' },
  { value: '研一', label: '研一' },
  { value: '研二', label: '研二' },
  { value: '研三', label: '研三' }
];
    // 方法定义
    const handleAvatarChange = (file) => {
      const isImage = ['image/jpeg', 'image/png'].includes(file.raw.type);
      const isLt2M = file.raw.size / 1024 / 1024 < 2;

      if (!isImage) {
        ElMessage.error('只能上传JPG/PNG格式的图片!');
        return;
      }
      if (!isLt2M) {
        ElMessage.error('头像图片大小不能超过2MB!');
        return;
      }

      avatarFile.value = file.raw;
      avatarPreview.value = URL.createObjectURL(file.raw);
    };
    const fetchSchools = async (queryString, cb) => {
      if (!queryString) return cb([]);
      try {
        const response = await axios.get('http://localhost:8092/school/list');
        const results = response.data.filter((school) =>
          school.schoolname.toLowerCase().includes(queryString.toLowerCase())
        );
        cb(results.map((school) => ({ value: school.schoolname })));
      } catch (error) {
        console.error('Error fetching schools:', error);
        cb([]);
      }
    };

    // 新增学校选择处理
    const handleSchoolSelect = (school) => {
      schoolInput.value = school.value;
    };
    const validatePassword = () => {
      isPasswordValid.value = passwordRegex.test(registerPassword.value);
    };

    const toggleRegisterPasswordVisibility = () => {
      showRegisterPassword.value = !showRegisterPassword.value;
    };

    const toggleConfirmPasswordVisibility = () => {
      showConfirmPassword.value = !showConfirmPassword.value;
    };

    const closeDialog = () => {
      emit('close');
    };

    const fetchMajors = async (queryString, cb) => {
      if (!queryString) return cb([]);
      try {
        const response = await axios.get('http://localhost:8092/major/list');
        const results = response.data.filter((major) =>
          major.majorname.toLowerCase().includes(queryString.toLowerCase())
        );
        cb(results.map((major) => ({ value: major.majorname })));
      } catch (error) {
        console.error('Error fetching majors:', error);
        cb([]);
      }
    };

    const handleMajorSelect = (major) => {
      majorInput.value = major.value;
    };

    const processRegister = async () => {
      if (!validateForm()) return;

      const formData = new FormData();
      formData.append('username', registerUsername.value);
      formData.append('nickname', nickname.value);
      formData.append('number', number.value);
      formData.append('sex', sex.value);
      formData.append('major', majorInput.value);
       formData.append('school', schoolInput.value);
      formData.append('grade', grade.value);
      formData.append('password', registerPassword.value);
      formData.append('role', number.value.startsWith('2') ? '01' : '02');
      if (avatarFile.value) {
        formData.append('avatarFile', avatarFile.value);
      }

      try {
        const response = await axios.post('http://localhost:8092/user/register', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        });

        if (response.data.code === 200) {
          ElMessage.success({
            message: '注册成功，请等待管理员审核，预计需要1-2个工作日',
            duration: 5000 // 延长显示时间
          });
          closeDialog();
      }else {
          ElMessage.error(response.data.msg || '注册失败');
        }
      } catch (error) {
        const message = error.response?.data?.message || '注册失败，请检查输入';
        ElMessage.error(message);
      }
    };

    const validateForm = () => {
      if (!registerUsername.value || 
          !nickname.value || 
          !number.value || 
          !sex.value || 
          !schoolInput.value || 
          !grade.value ||
          !isPasswordValid.value) {
        ElMessage.error('请填写所有必填字段并确保密码符合要求！');
        return false;
      }
      if (registerPassword.value !== confirmPassword.value) {
        ElMessage.error('两次密码输入不一致！');
        return false;
      }
      return true;
    };

    return {
       schoolInput,
      fetchSchools,
      handleSchoolSelect,
      registerUsername,
      nickname,
      number,
      sex,
      majorInput,
      registerPassword,
      confirmPassword,
      avatarPreview,
      showRegisterPassword,
      showConfirmPassword,
      isPasswordValid,
      sexOptions,
      grade,
      gradeOptions,
      handleAvatarChange,
      processRegister,
      validatePassword,
      toggleRegisterPasswordVisibility,
      toggleConfirmPasswordVisibility,
      closeDialog,
      fetchMajors,
      handleMajorSelect
    };
  },
});
</script>

<style scoped>
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal {
  background-color: white;
  padding: 30px;
  border-radius: 8px;
  width: 400px;
  height: auto;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  position: relative;
}

.modal-close-button {
  position: absolute;
  top: 10px;
  right: 10px;
  font-size: 24px;
  cursor: pointer;
}

.input-group {
  margin-bottom: 20px;
  position: relative;
}

.toggle-password {
  cursor: pointer;
  font-size: 18px;
}

.error-message {
  color: red;
  font-size: 12px;
}

.el-button {
  margin-top: 20px;
  width: 100%;
}

.avatar-upload {
  text-align: center;
  margin-bottom: 20px;
}

.avatar-uploader {
  display: inline-block;
  position: relative;
  cursor: pointer;
  border: 2px dashed #dcdfe6;
  border-radius: 50%;
  overflow: hidden;
  width: 120px;
  height: 120px;
  transition: border-color 0.3s;
}

.avatar-uploader:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 32px;
  color: #8c939d;
  margin: 34px 0;
}

.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.upload-hint {
  position: absolute;
  bottom: -30px;
  width: 100%;
  text-align: center;
  font-size: 12px;
  color: #606266;
}

.avatar-tips {
  margin-top: 10px;
  font-size: 12px;
  color: #909399;
}

.input-error {
  border-color: red;
}
.full-width-select {
  width: 100%;
}
</style>